require('./Uploadimg.styl');
import Icon from 'salt-icon';
import { Boxs } from 'saltui'
const { HBox, Box, VBox } = Boxs;
class Uploadimg extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            src: ''
        };
        this.handleClickBtn = this.handleClickBtn.bind(this);
        this.fileChoose = this.fileChoose.bind(this);
        this.handleClickDelBtn = this.handleClickDelBtn.bind(this);
    }
    //读取文件
    fileChoose() {
        var file = this.imageInput.files[0];   //读取文件
        let reader = new FileReader();
        let t = this;
        t.formData = new FormData(this.refs.imageForm);
        reader.onload = function () {
            // var result = this.result;  //result为data url的形式
            t.setState({ src: this.result });
        }
        reader.readAsDataURL(file);//读取到的文件编码成Data URL,base64
    }
    handleClickBtn() {
        // let imageInput = this.refs.imageInput.getDOMNode();
        this.imageInput.click();
    }
    handleClickDelBtn() {
        this.setState({ src: '' })
    }
    render() {
        return (
            <div className="uploadimg">
                <div className="t-ML16 t-MT8 t-MB10">图片</div>
                <HBox className="t-ML20 box">
                    <form className="image-Form" ref="imageForm" >
                        <input
                            className="image-Input"
                            type="file"
                            name="file"
                            accept="image/png,image/jpg,image/jpeg"
                            ref={(input) => { this.imageInput = input }}
                            onChange={this.fileChoose}
                        />
                    </form>
                    <Box className="img-box">
                        {this.state.src ?
                            <HBox>
                                <Box>
                                    <Icon className="icon-cross-round" name="cross-round" width="20" height="20" fill="red" onClick={this.handleClickDelBtn}/>
                                    <p><img className="my-img" src={this.state.src} alt="" /></p>
                                </Box>
                            </HBox>
                            :
                            <div className="upload-img" >
                                <Icon name="plus-thin" width="80" fill="white"  />
                            </div>
                        }
                    </Box>
                </HBox>
            </div>
        );
    }

    componentWillMount() {
    }

    componentDidMount() {
    }

    componentWillReceiveProps(nextProps) {
    }

    shouldComponentUpdate(nextProps, nextState) {
        return true;
    }

    componentWillUpdate(nextProps, nextState) {
    }

    componentDidUpdate(prevProps, prevState) {
    }

    componentWillUnmount() {
    }
}

module.exports = Uploadimg;
